<template>
    <div v-if="!$route.query.id || ($route.query.id && detail)">
        <div class="vs-search-box">
            <template v-if="type == 1">
                <el-form :model="form" style="width: 1000px" label-width="100px">
                    <el-form-item :label="$route.path=='/goodsAllotInfo'?'调拨单状态':'退货单状态'">
                        <span class="tab-red-text status">{{ statusFilter(this.detail.row.status) }}</span>
                        <el-button class="fl-right" v-if="detail.row.status == 1 || detail.row.status == 4" @click="dialogVisible = true" type="primary">填写物流信息</el-button>
                        <el-button class="fl-right" @click="cancel" v-if="detail.row.status == 3 && detail.row.from_store_id == userInfo.store_id" type="danger" plain>撤回</el-button>
                        <el-button class="fl-right" @click="confirm" v-if="detail.row.status == 3 && detail.row.from_store_id != userInfo.store_id" type="primary" plain>确认收货</el-button>
                    </el-form-item>
                    <template v-if="detail.logistics && JSON.stringify(detail.logistics) != '[]'">
                        <el-descriptions title="物流信息" border :column="2">
                            <el-descriptions-item label="物流公司">{{ detail.logistics.company }}</el-descriptions-item>
                            <el-descriptions-item label="物流单号">{{ detail.logistics.number }}</el-descriptions-item>
                            <el-descriptions-item label="备注">{{ detail.logistics.remarks }}</el-descriptions-item>
                        </el-descriptions>
                    </template>
                    <template v-if="detail.row.status">
                        <el-descriptions title="操作信息" border style="margin: 20px 0" :column="2">
                            <el-descriptions-item label="审核人员">{{ detail.row.examine.realname }}</el-descriptions-item>
                            <el-descriptions-item label="审核时间">{{ detail.row.examine_date }}</el-descriptions-item>
                            <el-descriptions-item label="备注">{{ detail.row.examine_remarks }}</el-descriptions-item>
                        </el-descriptions>
                    </template>
                </el-form>
                <el-descriptions title="" border :column="2" style="width: 1000px">
                    <el-descriptions-item label="调拨单号">{{ detail.row.number }}</el-descriptions-item>
                    <el-descriptions-item label="调出门店" v-if="detail.row.fromStore">{{ detail.row.fromStore.title }}</el-descriptions-item>
                    <el-descriptions-item label="调入门店" v-if="detail.row.toStore">{{ detail.row.toStore.title }}</el-descriptions-item>
                    <el-descriptions-item label="商品类型">{{ detail.row.goods_type | typeFilter }}</el-descriptions-item>
                    <el-descriptions-item label="单据备注">
                        {{ detail.row.remarks }}
                    </el-descriptions-item>
                </el-descriptions>
            </template>
            <el-form v-else :model="form" ref="form" :rules="rules" style="width: 720px" inline label-width="100px">
                <el-form-item label="调拨单号">
                    <el-input readonly value="系统自动生成" style="width: 250px" placeholder="系统自动生成"></el-input>
                </el-form-item>
                <el-form-item label="调出门店">
                    <el-input :value="userInfo.store.title" readonly style="width: 250px" placeholder="请选择"></el-input>
                </el-form-item>
                <el-form-item label="调入门店" prop="to_store_id">
                    <el-select v-model="form.to_store_id" placeholder="请选择" filterable style="width: 250px">
                        <el-option v-for="item in storeList" :key="item.id" :label="item.title" :disabled="userInfo.store_id == item.id" :value="item.id + ''"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品类型" prop="goods_type">
                    <el-select v-model="form.goods_type" @change="proChange" placeholder="请选择" style="width: 250px">
                        <el-option label="毛坯" value="1"> </el-option>
                        <el-option label="定制成品" value="2"> </el-option>
                        <el-option label="标准成品" value="6"> </el-option>
                        <!-- <el-option label="积分商品" value="3"> </el-option> -->
                        <el-option label="洗护用品" value="4"> </el-option>
                        <el-option label="其他" value="5"> </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="单据备注" class="vs-form-item-100">
                    <el-input v-model="form.remarks" :rows="4" type="textarea" placeholder=""></el-input>
                </el-form-item>
            </el-form>
        </div>
        <div class="vs-table-box" v-if="type == 2">
            <div class="operation-box clear-float">
                <el-button @click="goodsChange" type="primary">选择商品</el-button>
            </div>
            <el-table key="1" v-if="beType == 1" :data="form.allocation_info" header-row-class-name="has-gutter-table" style="margin-top: 20px" :summary-method="getSummaries" show-summary border ref="multipleTable">
                <el-table-column type="index" width="100px" label="序号" align="center"></el-table-column>
                <el-table-column prop="number" label="商品编码" align="center"></el-table-column>
                <el-table-column prop="title" label="产品名称" align="center"></el-table-column>
                <el-table-column prop="roughcast" label="毛坯种类" align="center"></el-table-column>
                <template v-if="form.goods_type == 6">
                    <el-table-column prop="item" label="款号" align="center" :key="3"> </el-table-column>
                </template>
                <template v-if="form.goods_type == 1 || form.goods_type == 2">
                    <el-table-column prop="needle" label="递针类型" align="center"> </el-table-column>
                    <el-table-column prop="sex" label="性别" align="center"> </el-table-column>
                    <el-table-column prop="length" label="长度" align="center"> </el-table-column>
                </template>
                <el-table-column prop="size" label="尺寸" align="center"> </el-table-column>
                <el-table-column prop="colour" label="颜色" align="center"> </el-table-column>
                <!-- <el-table-column prop="stock_info.0.price" label="调拨单价"  align="center" ></el-table-column> -->
                <el-table-column prop="stock_count" label="库存数量" align="center"></el-table-column>
                <el-table-column prop="count" label="调拨数量" align="center">
                    <template slot-scope="scope">
                        <el-input v-enter-money="0" v-model="scope.row.count" placeholder=""></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="调拨单价" align="center">
                    <!-- <template slot-scope="scope">
                {{calculate(scope.row)}}
            </template> -->
                    <template slot-scope="scope">
                        <el-input v-enter-money="0" @blur="priceBlur($event, scope.$index)" type="number" v-model="scope.row.price" placeholder=""></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="remarks" label="备注" align="center">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.remarks" placeholder=""></el-input>
                    </template>
                </el-table-column>
                <el-table-column v-if="type == 2" label="操作" width="120" align="center">
                    <template slot-scope="scope">
                        <!-- <span class="tab-table-text">添加</span> -->
                        <span @click="form.allocation_info.splice(scope.$index, 1)" class="tab-red-text">删除</span>
                    </template>
                </el-table-column>
            </el-table>
            <el-table v-if="beType == 2" :data="form.allocation_info" header-row-class-name="has-gutter-table" style="width: 1000px; margin-top: 20px" show-summary border key="2" ref="multipleTable" :summary-method="getSummaries">
                <el-table-column type="index" width="100px" label="序号" align="center"></el-table-column>
                <el-table-column prop="number" label="商品编码" align="center"></el-table-column>
                <el-table-column prop="title" label="商品系列" align="center"></el-table-column>
                <el-table-column prop="spce" label="规格" align="center"></el-table-column>
                <el-table-column prop="unit" label="单位" align="center"></el-table-column>
                <el-table-column prop="stock_count" label="库存数量" align="center"></el-table-column>
                <!-- <el-table-column prop="tech_num" label="调拨单价"  align="center"></el-table-column> -->
                <el-table-column prop="count" label="调拨数量" align="center">
                    <template slot-scope="scope">
                        <el-input v-enter-money="0" v-model="scope.row.count" placeholder=""></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="price" label="调拨单价" align="center">
                    <!-- <template slot-scope="scope">
                {{calculate(scope.row)}}
            </template> -->
                    <template slot-scope="scope">
                        <el-input v-enter-money="0" @blur="priceBlur($event, scope.$index)" type="number" v-model="scope.row.price" placeholder=""></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="remarks" label="备注" align="center">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.remarks" placeholder=""></el-input>
                    </template>
                </el-table-column>
                <el-table-column v-if="type == 2" label="操作" width="120" align="center">
                    <template slot-scope="scope">
                        <!-- <span class="tab-table-text">添加</span> -->
                        <span @click="form.allocation_info.splice(scope.$index, 1)" class="tab-red-text">删除</span>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!--  -->
        <div class="vs-table-box" v-if="type == 1">
            <el-table
            v-if="detail.row.goods_type == 1 || detail.row.goods_type == 2 || detail.row.goods_type == 6" 
            :data="detail.info"
            show-summary
            :summary-method="getSummaries"
            header-row-class-name="has-gutter-table"
            style="margin-top: 20px"
            border
            key="3"
            ref="multipleTable">
                <el-table-column type="index" width="100px" label="序号" align="center"></el-table-column>
                <el-table-column prop="number" label="商品编码" align="center"></el-table-column>
                <el-table-column prop="title" label="产品名称" align="center"></el-table-column>
                <el-table-column prop="roughcast" label="毛坯种类" align="center"></el-table-column>
                <template v-if="detail.row.goods_type == 6">
                    <el-table-column prop="item" label="款号" align="center" :key="3"> </el-table-column>
                </template>
                <template v-if="detail.row.goods_type == 1 || detail.row.goods_type == 2">
                    <el-table-column prop="needle" label="递针类型" align="center"> </el-table-column>
                    <el-table-column prop="sex" label="性别" align="center"> </el-table-column>
                    <el-table-column prop="length" label="长度" align="center"> </el-table-column>
                </template>
                <el-table-column prop="size" label="尺寸" align="center"> </el-table-column>
                <el-table-column prop="colour" label="颜色" align="center"> </el-table-column>
                <el-table-column prop="price" label="调拨单价" align="center"></el-table-column>
                <el-table-column prop="count" label="调拨数量" align="center"></el-table-column>
                <el-table-column prop="total_price" label="调拨金额" align="center"></el-table-column>
                <el-table-column prop="remarks" label="备注" align="center"></el-table-column>
            </el-table>
            <el-table v-else :data="detail.info" header-row-class-name="has-gutter-table" style="width: 1000px; margin-top: 20px" show-summary  border key="4" ref="multipleTable">
                <el-table-column type="index" width="100px" label="序号" align="center"></el-table-column>
                <el-table-column prop="number" label="商品编码" align="center"></el-table-column>
                <el-table-column prop="title" label="商品系列" align="center"></el-table-column>
                <el-table-column prop="unit" label="单位" align="center"></el-table-column>
                <el-table-column prop="price" label="调拨单价" align="center"></el-table-column>
                <el-table-column prop="count" label="调拨数量" align="center"></el-table-column>
                <el-table-column prop="total_price" label="调拨金额" align="center"></el-table-column>
                <el-table-column prop="remarks" label="备注" align="center"></el-table-column>
            </el-table>
        </div>

        <el-dialog title="填写物流信息" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false" :before-close="handleClose">
            <el-form :model="form1" ref="form1" :rules="rules1" label-width="100px">
                <el-form-item label="物流公司" prop="company">
                    <el-input v-model="form1.company" placeholder="请输入物流公司"></el-input>
                </el-form-item>
                <el-form-item label="物流单号" prop="number">
                    <el-input v-model="form1.number" placeholder="请输入物流单号"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="remarks">
                    <el-input v-model="form1.remarks" placeholder="请输入备注"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="commit">确 定</el-button>
            </span>
        </el-dialog>
        <choice-goods :isStock="true" v-if="isGoods" :showStock="true" :type="form.goods_type" v-model="isGoods" @change="changeGoods"></choice-goods>

        <div class="vs-bottom-btns">
            <el-button @click="utils.backPage()" class="vs-w-130">返回</el-button>
            <el-button type="primary" class="vs-m-l-40 vs-w-130" :loading="isBtn" v-if="type == 2" @click="allocationOrderAdd">确 定</el-button>
        </div>
    </div>
</template>

<script>
    import ChoiceGoods from '@/components/ChoiceGoods.vue';
    import { number } from 'echarts';

    export default {
        components: { ChoiceGoods },
        data() {
            return {
                detail: {
                    info: [],
                    logistics: [],
                    row: [],
                },
                userInfo: {},
                type: 1, //1详情  2新增
                beType: 1, //商品类型 1标准毛坯   2洗护商品/其他
                isBtn: false,
                form: {
                    id: '',
                    goods_type: '', //物料类型
                    remarks: '', //备注
                    allocation_info: [], //具体物料信息
                    from_store_id: '', //来源门店id
                    to_store_id: '', //调入门店id
                },
                rules: {
                    goods_type: { required: true, message: '请选择商品类型', trigger: 'change' },
                    to_store_id: { required: true, message: '请选择调入门店', trigger: 'change' },
                },
                isGoods: false,
                dialogVisible: false,
                categoryList: [],
                storeList: [],
                tableData: [
                    {
                        tech_num: 10,
                    },
                ],
                form1: {
                    remarks: '',
                    number: '',
                    company: '',
                },
                rules1: {
                    company: { required: true, message: '请输入物流公司', trigger: 'blur' },
                    number: { required: true, message: '请输入物流单号', trigger: 'blur' },
                },
            };
        },
        computed: {
            proType() {
                let arr = ['0', '1', '5', '2', '3', '4'];
                return arr[this.form.goods_type || 0];
            },
        },
        filters: {
            typeFilter(val) {
                let arr = ['毛坯', '定制成品', '积分商品', '洗护用品', '其他', '标准成品'];
                return arr[val - 1];
            },
        },
        created() {
            let { type = 1, beType = 1, id } = this.$route.query;
            this.type = type;
            this.beType = beType;
            this.$route.meta.title = this.utils.typeTitle(type, '调拨单');
            this.getGoodsCategoryList();
            this.getStore();
            this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
            if (type == 1) {
                this.form.from_store_id = this.userInfo.store_id;
            }
            if (id) {
                this.getDetail(id);
            }
        },
        methods: {
            statusFilter(val) {
                let arr1 = ['待审核', '待出库', '已驳回', '已出库', '已撤回', '已入库'];
                let arr2 = ['待审核', '待出库', '已驳回', '待入库', '已撤回', '已入库'];
                if (this.detail.row.from_store_id == this.userInfo.store_id) {
                    return arr1[val || 0];
                } else {
                    return arr2[val || 0];
                }
            },
            goodsChange() {
                if (!this.form.goods_type) {
                    return this.$message.warning('请选择产品类型');
                } else if (!this.form.to_store_id) {
                    return this.$message.warning('请选择入库门店');
                }
                this.isGoods = true;
            },
            commit() {
                this.$refs['form1'].validate(async (valid) => {
                    if (!valid) return;
                    let { code } = await this.$Http.allocationOrderLogistics({
                        allocation_orders_id: this.$route.query.id,
                        company: this.form1.company,
                        number: this.form1.number,
                        remarks: this.form1.remarks,
                    });

                    if (code) {
                        this.$message.success('操作成功');
                        this.dialogVisible = false;
                        this.getDetail(this.$route.query.id);
                    }
                });
            },
            // 确认收货
            confirm() {
                this.$confirm('是否确认收货？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                })
                    .then(async () => {
                        let { code } = await this.$Http.allocationOrderArrival({
                            id: this.$route.query.id,
                        });
                        if (code) {
                            this.$message.success('操作成功');
                            this.utils.backPage();
                            // setTimeout(() => {
                            //     this.repairGetList();
                            // }, 1000);
                        }
                    })
                    .catch(() => {});
            },
            cancel() {
                this.$confirm('是否确认撤回此调拨单？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                })
                    .then(async () => {
                        let parms = {
                            allocation_orders_id: this.$route.query.id,
                            number: this.detail.logistics.number,
                            remarks: this.detail.logistics.remarks,
                            company: this.detail.logistics.company,
                        };
                        let info = [];
                        for (let i in this.detail.info) {
                            info.push({
                                id: this.detail.info[i].id,
                                revoke_count: this.detail.info[i].count,
                            });
                        }
                        parms.info = JSON.stringify(info);
                        let { code } = await this.$Http.allocationOrderRevoke(parms);
                        if (code) {
                            this.$message.success('撤回成功');
                            this.utils.backPage();
                            // setTimeout(() => {
                            //     this.repairGetList();
                            // }, 1000);
                        }
                    })
                    .catch(() => {});
            },
            priceBlur(e, i) {
                this.form.allocation_info[i].price = parseFloat(Math.abs(this.form.allocation_info[i].price)).toFixed(2);
            },
            async getDetail(id) {
                let { code, data } = await this.$Http.allocationOrderInfo({ id });
                if (code) {
                    this.detail = data;
                    // this.form.allocation_info = data.info
                    if (this.type == 2) {
                        // 编辑回显
                        this.form.id = id;
                        this.form.from_store_id = data.row.from_store_id;
                        this.form.to_store_id = data.row.to_store_id + '';
                        this.form.goods_type = data.row.goods_type + '';
                        this.form.remarks = data.row.remarks;
                        this.form.allocation_info = data.info;
                    }
                }
            },
            // 类型切换
            proChange() {
                this.form.allocation_info = [];
                if (this.form.goods_type == 1 || this.form.goods_type == 2 || this.form.goods_type == 6) {
                    this.beType = 1;
                } else {
                    this.beType = 2;
                }
            },
            allocationOrderAdd() {
                this.$refs['form'].validate(async (valid) => {
                    if (!valid) return;
                    let obj = Object.assign({}, this.form);
                    if (!obj.allocation_info.length) return this.$message.error('请选择要调拨的商品!');

                    let bol = obj.allocation_info.find((v) => v.count == '');
                    if (bol) return this.$message.error('请输入数量');

                    obj.allocation_info = JSON.stringify(
                        obj.allocation_info.map((v) => {
                            let stock_info = v.stock_info && v.stock_info.length ? v.stock_info[0] : {};
                            return {
                                goods_id: v.goods_id,
                                purchase_id: stock_info.purchase_id || 0,
                                count: v.count,
                                price: v.price || 0,
                                remarks: v.remarks,
                            };
                        })
                    );
                    obj.from_store_id = this.userInfo.store_id;
                    this.isBtn = true;
                    let { code } = await this.$Http.allocationOrderAdd(obj);
                    this.isBtn = false;
                    if (code) {
                        this.$message.success('调拨成功!');
                        this.utils.backPage();
                    }
                });
            },
            calculate(row) {
                let zoprice = 0.0;
                if (row.stock_info && row.stock_info.length) {
                    let price = row.stock_info[0].price || 0;
                    zoprice = price * row.count || 0;
                }
                row.zoPrice = zoprice;
                return zoprice;
            },
            getSummaries(param) {
                const { columns, data } = param;
                const sums = [];
                columns.forEach((column, index) => {
                    if (index === 0) {
                        sums[index] = '合计';
                        return;
                    }
                    const values = data.map((item) => Number(item[column.property]));
                    if (column.property == 'count' || column.property == 'zoPrice' || column.property == 'price') {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;
                            } else {
                                return prev;
                            }
                        }, 0);
                    } else {
                        sums[index] = '';
                    }
                });
                return sums;
            },
            changeGoods(list) {
                console.log(list);
                list.map((v) => {
                    v.goods_id = v.id;
                    // v.stock_info = [{price:8.75}];
                    v.count = '';
                    v.price = '';
                    v.remarks = '';
                    // v.zoPrice = 0;
                    if (!this.form.allocation_info.find((v2) => v2.goods_id == v.id)) {
                        this.form.allocation_info.push({ ...v });
                    }
                });
                // [{"goods_id":1,"purchase_id":1,"count":1,"price":2,"remarks":"测试"}]
            },
            async getStore() {
                let { code, data } = await this.$Http.getStore({ limit: 999999 });
                if (code) {
                    this.storeList = data.data;
                }
            },
            async getGoodsCategoryList() {
                let { code, data } = await this.$Http.getGoodsCategoryList({ special_type: 1 });
                if (code) {
                    this.categoryList = data;
                }
            },
            handleClose(dom) {
                dom && dom();
            },
        },
    };
</script>

<style leng="scss" scoped>
    .status {
        font-size: 18px;
        cursor: default;
    }
</style>
